const StockHistoryService = require('./StockHistoryService');

class StockDataScheduler {
  constructor() {
    this.intervalId = null;
    this.watchlist = ['000001', '600000', '600036', '600519', '000858']; // 默认关注的股票代码
  }

  // 设置关注的股票列表
  setWatchlist(stockSymbols) {
    this.watchlist = stockSymbols;
  }

  // 开始定时任务
  start(intervalMinutes = 60) {
    if (this.intervalId) {
      console.log('Stock data scheduler is already running');
      return;
    }

    console.log(`Starting stock data scheduler, updating every ${intervalMinutes} minutes`);
    
    // 立即执行一次
    this.updateAllStocks();
    
    // 设置定时任务
    this.intervalId = setInterval(() => {
      this.updateAllStocks();
    }, intervalMinutes * 60 * 1000); // 转换为毫秒
  }

  // 停止定时任务
  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
      console.log('Stock data scheduler stopped');
    }
  }

  // 更新所有关注的股票数据
  async updateAllStocks() {
    console.log('Updating stock history data for watchlist:', this.watchlist);
    
    for (const symbol of this.watchlist) {
      try {
        await StockHistoryService.fetchAndStoreHistory(symbol, 'daily');
        console.log(`Successfully updated history data for ${symbol}`);
        
        // 添加延迟以避免API限制
        await this.delay(1000);
      } catch (error) {
        console.error(`Failed to update history data for ${symbol}:`, error.message);
      }
    }
    
    console.log('Finished updating all stock history data');
  }

  // 延迟函数
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

module.exports = new StockDataScheduler();